"""
智能客服路由
提供智能客服助理的API接口
"""

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from typing import List, Dict, Any, Optional
from pydantic import BaseModel
import uuid
import json
import base64
from datetime import datetime

from src.services.chatbot_service import (
    ChatbotService, 
    ChatResponse,
    create_chat_session,
    get_chat_session,
    add_message_to_session
)
from src.services.ticket_service import TicketService
# 修复导入问题，使用容器获取知识库服务
# from src.services.knowledge_base_service import get_knowledge_base_service
from src.containers import get_knowledge_base_service
from src.models.chat import ChatMessage, ChatSessionResponse
from src.models.ticket import TicketCreate, TicketCategory, TicketPriority
from src.models.user import User
from src.services.auth_service import get_current_active_user_dep
from src.utils.logging import get_logger
from src.config.database import get_db

logger = get_logger(__name__)

router = APIRouter(prefix="/chatbot", tags=["智能客服"])

class ChatRequest(BaseModel):
    message: str
    session_id: Optional[str] = None
    context: Optional[Dict[str, Any]] = None

class ChatImageRequest(BaseModel):
    image_data: str  # Base64编码的图像数据
    session_id: Optional[str] = None
    context: Optional[Dict[str, Any]] = None

class ChatVoiceRequest(BaseModel):
    audio_data: str  # Base64编码的音频数据
    session_id: Optional[str] = None
    context: Optional[Dict[str, Any]] = None

class ChatVideoRequest(BaseModel):
    video_data: str  # Base64编码的视频数据
    session_id: Optional[str] = None
    context: Optional[Dict[str, Any]] = None

class ChatSessionResponse(BaseModel):
    session_id: str
    messages: List[ChatMessage]
    created_at: datetime

class KnowledgeSuggestionRequest(BaseModel):
    query: str
    limit: int = 5

class FeedbackRequest(BaseModel):
    session_id: str
    message_id: str
    rating: int  # 1-5分
    comment: Optional[str] = None

class TicketCreationRequest(BaseModel):
    title: str
    description: str
    category: str = "general"
    priority: str = "medium"

@router.post("/sessions", response_model=ChatSessionResponse)
async def create_chat_session_endpoint(
    current_user: User = Depends(get_current_active_user_dep)
):
    """创建新的聊天会话"""
    try:
        session = create_chat_session(str(current_user.id))
        return ChatSessionResponse(
            session_id=session.session_id,
            messages=[],
            created_at=session.created_at
        )
    except Exception as e:
        logger.error(f"创建聊天会话失败: {e}")
        raise HTTPException(status_code=500, detail="创建聊天会话失败")

@router.get("/sessions/{session_id}", response_model=ChatSessionResponse)
async def get_chat_session_endpoint(
    session_id: str,
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取聊天会话详情"""
    try:
        session = get_chat_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话未找到")
        
        # 检查用户权限
        if session.user_id != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权访问此会话")
            
        return ChatSessionResponse(
            session_id=session.session_id,
            messages=session.messages,
            created_at=session.created_at
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取聊天会话失败: {e}")
        raise HTTPException(status_code=500, detail="获取聊天会话失败")

@router.post("/chat", response_model=ChatResponse)
async def chat_with_bot(
    request: ChatRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """与智能客服聊天"""
    try:
        # 如果没有提供session_id，创建新的会话
        if not request.session_id:
            session = create_chat_session(str(current_user.id))
            session_id = session.session_id
        else:
            session_id = request.session_id
            # 验证会话存在且属于当前用户
            session = get_chat_session(session_id)
            if not session:
                raise HTTPException(status_code=404, detail="会话未找到")
            if session.user_id != str(current_user.id):
                raise HTTPException(status_code=403, detail="无权访问此会话")
        
        # 添加用户消息到会话
        user_message = ChatMessage(
            role="user",
            content=request.message,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, user_message)
        
        # 获取智能客服响应
        service = ChatbotService()
        response = service.process_message(
            message=request.message,
            session_id=session_id,
            context=request.context or {},
            user_id=str(current_user.id)
        )
        
        # 添加助手消息到会话
        assistant_message = ChatMessage(
            role="assistant",
            content=response.response,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, assistant_message)
        
        return response
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理聊天消息失败: {e}")
        raise HTTPException(status_code=500, detail="处理聊天消息失败")

@router.post("/chat-image", response_model=ChatResponse)
async def chat_with_image(
    request: ChatImageRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """处理图像聊天消息"""
    try:
        # 如果没有提供session_id，创建新的会话
        if not request.session_id:
            session = create_chat_session(str(current_user.id))
            session_id = session.session_id
        else:
            session_id = request.session_id
            # 验证会话存在且属于当前用户
            session = get_chat_session(session_id)
            if not session:
                raise HTTPException(status_code=404, detail="会话未找到")
            if session.user_id != str(current_user.id):
                raise HTTPException(status_code=403, detail="无权访问此会话")
            
        # 解码图像数据
        image_data = base64.b64decode(request.image_data)
        
        # 处理图像消息
        service = ChatbotService()
        image_description = service.process_image_message(image_data, session_id)
        
        # 添加用户图像消息到会话
        user_message = ChatMessage(
            role="user",
            content=image_description,
            content_type="image",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, user_message)
        
        # 基于图像描述生成响应
        response = service.process_message(
            message=image_description,
            session_id=session_id,
            context=request.context or {},
            user_id=str(current_user.id)
        )
        
        # 添加助手消息到会话
        assistant_message = ChatMessage(
            role="assistant",
            content=response.response,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, assistant_message)
        
        return response
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理图像聊天消息失败: {e}")
        raise HTTPException(status_code=500, detail="处理图像聊天消息失败")

@router.post("/chat-voice", response_model=ChatResponse)
async def chat_with_voice(
    request: ChatVoiceRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """处理语音聊天消息"""
    try:
        # 如果没有提供session_id，创建新的会话
        if not request.session_id:
            session = create_chat_session(str(current_user.id))
            session_id = session.session_id
        else:
            session_id = request.session_id
            # 验证会话存在且属于当前用户
            session = get_chat_session(session_id)
            if not session:
                raise HTTPException(status_code=404, detail="会话未找到")
            if session.user_id != str(current_user.id):
                raise HTTPException(status_code=403, detail="无权访问此会话")
            
        # 解码音频数据
        audio_data = base64.b64decode(request.audio_data)
        
        # 处理语音消息
        service = ChatbotService()
        transcribed_text = await service.process_voice_message(audio_data, session_id)
        
        # 添加用户语音消息到会话
        user_message = ChatMessage(
            role="user",
            content=transcribed_text,
            content_type="audio",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, user_message)
        
        # 基于转录文本生成响应
        response = service.process_message(
            message=transcribed_text,
            session_id=session_id,
            context=request.context or {},
            user_id=str(current_user.id)
        )
        
        # 添加助手消息到会话
        assistant_message = ChatMessage(
            role="assistant",
            content=response.response,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, assistant_message)
        
        return response
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理语音聊天消息失败: {e}")
        raise HTTPException(status_code=500, detail="处理语音聊天消息失败")

@router.post("/chat-video", response_model=ChatResponse)
async def chat_with_video(
    request: ChatVideoRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """处理视频聊天消息"""
    try:
        # 如果没有提供session_id，创建新的会话
        if not request.session_id:
            session = create_chat_session(str(current_user.id))
            session_id = session.session_id
        else:
            session_id = request.session_id
            # 验证会话存在且属于当前用户
            session = get_chat_session(session_id)
            if not session:
                raise HTTPException(status_code=404, detail="会话未找到")
            if session.user_id != str(current_user.id):
                raise HTTPException(status_code=403, detail="无权访问此会话")
            
        # 解码视频数据
        video_data = base64.b64decode(request.video_data)
        
        # 处理视频消息
        service = ChatbotService()
        video_description = service.process_video_message(video_data, session_id)
        
        # 添加用户视频消息到会话
        user_message = ChatMessage(
            role="user",
            content=video_description,
            content_type="video",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, user_message)
        
        # 基于视频描述生成响应
        response = service.process_message(
            message=video_description,
            session_id=session_id,
            context=request.context or {},
            user_id=str(current_user.id)
        )
        
        # 添加助手消息到会话
        assistant_message = ChatMessage(
            role="assistant",
            content=response.response,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, assistant_message)
        
        return response
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理视频聊天消息失败: {e}")
        raise HTTPException(status_code=500, detail="处理视频聊天消息失败")

@router.post("/chat-stream")
async def chat_with_bot_stream(
    request: ChatRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """流式与智能客服聊天"""
    try:
        # 如果没有提供session_id，创建新的会话
        if not request.session_id:
            session = create_chat_session(str(current_user.id))
            session_id = session.session_id
        else:
            session_id = request.session_id
            # 验证会话存在且属于当前用户
            session = get_chat_session(session_id)
            if not session:
                raise HTTPException(status_code=404, detail="会话未找到")
            if session.user_id != str(current_user.id):
                raise HTTPException(status_code=403, detail="无权访问此会话")
        
        # 添加用户消息到会话
        user_message = ChatMessage(
            role="user",
            content=request.message,
            content_type="text",
            timestamp=datetime.now()
        )
        add_message_to_session(session_id, user_message)
        
        # 获取智能客服响应流
        service = ChatbotService()
        
        async def event_generator():
            full_response = ""
            async for chunk in service.process_message_stream(
                message=request.message,
                session_id=session_id,
                context=request.context or {},
                user_id=str(current_user.id)
            ):
                full_response += chunk
                yield f"data: {json.dumps({'chunk': chunk})}\n\n"
            
            # 添加完整响应到会话
            assistant_message = ChatMessage(
                role="assistant",
                content=full_response,
                content_type="text",
                timestamp=datetime.now()
            )
            add_message_to_session(session_id, assistant_message)
            yield "data: [DONE]\n\n"
        
        return StreamingResponse(event_generator(), media_type="text/event-stream")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理流式聊天消息失败: {e}")
        raise HTTPException(status_code=500, detail="处理流式聊天消息失败")

@router.post("/escalate-to-ticket")
async def escalate_to_ticket(
    request: TicketCreationRequest,
    current_user: User = Depends(get_current_active_user_dep),
    db = Depends(get_db)
):
    """将对话升级为工单"""
    try:
        # 创建工单
        ticket_data = TicketCreate(
            title=request.title,
            description=request.description,
            category=TicketCategory(request.category) if request.category in TicketCategory.__members__ else TicketCategory.GENERAL,
            priority=TicketPriority(request.priority) if request.priority in TicketPriority.__members__ else TicketPriority.MEDIUM,
        )
        
        ticket = TicketService.create_ticket(db, ticket_data, current_user)
        
        return {
            "message": "工单创建成功",
            "ticket_id": str(ticket.id),
            "status": ticket.status
        }
    except Exception as e:
        logger.error(f"升级为工单失败: {e}")
        raise HTTPException(status_code=500, detail="升级为工单失败")

@router.post("/knowledge-suggestions")
async def get_knowledge_suggestions(
    request: KnowledgeSuggestionRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取知识库建议"""
    try:
        kb_service = get_knowledge_base_service()
        # 这里可以实现更复杂的建议逻辑
        suggestions = kb_service.get_search_suggestions(request.query, request.limit)
        return suggestions
    except Exception as e:
        logger.error(f"获取知识建议失败: {e}")
        raise HTTPException(status_code=500, detail="获取知识建议失败")

@router.post("/feedback", response_model=Dict[str, str])
async def submit_chat_feedback(
    request: FeedbackRequest,
    current_user: User = Depends(get_current_active_user_dep)
):
    """提交聊天回答的反馈信息"""
    try:
        # 验证会话存在且属于当前用户
        session = get_chat_session(request.session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话未找到")
        if session.user_id != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权访问此会话")
        
        # 调用ChatbotService提交反馈
        service = ChatbotService()
        result = service.submit_feedback(
            session_id=request.session_id,
            message_id=request.message_id,
            rating=request.rating,
            comment=request.comment
        )
        
        if result["status"] == "error":
            raise HTTPException(status_code=400, detail=result["message"])
        
        return {"message": result["message"]}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"提交聊天反馈失败: {e}")
        raise HTTPException(status_code=500, detail="提交反馈失败")